package org.imlinker.sound;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;

import org.imlinker.account.ManageAccount;

/**
 * Sample clip player, only support uncompression file such as .wav.
 *  
 */

public class SoundPlayer implements LineListener {
	/**
	 * Sound.
	 */
	private static Clip revSound;

	/**
	 * The SoundPlayer.
	 */
	private static SoundPlayer soundLoader;

	/**
	 * PlaySound.
	 * 
	 * @param clipFile
	 *            The sound file.
	 * @param loop
	 *            The number of loops.
	 */
	public static void playSound(final File clipFile, final int loop) {
		AudioInputStream audioInputStream = null;
		File soundFile = clipFile;

		// temporary... just for message sound
		if (soundFile == null) {
			String path = ManageAccount.getPath() + File.separator + "sound"
					+ File.separator + "receive.wav";
			soundFile = new File(path);
		}

		try {
			audioInputStream = AudioSystem.getAudioInputStream(soundFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (audioInputStream != null) {
			AudioFormat format = audioInputStream.getFormat();
			DataLine.Info info = new DataLine.Info(Clip.class, format);
			try {
				revSound = (Clip) AudioSystem.getLine(info);
				revSound.open(audioInputStream);
			} catch (LineUnavailableException e) {
				return;
				// e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("Try a .wav file");
		}

		revSound.loop(loop);
	}

	/**
	 * Update event.
	 * 
	 * @param event
	 *            The lineEvent.
	 */
	public final void update(final LineEvent event) {
		if (event.getType().equals(LineEvent.Type.STOP)) {
			revSound.close();
		}
	}

	/**
	 * Get the soundPlayer.
	 * 
	 * @return The soundPlayer.
	 */
	public static SoundPlayer getInstance() {
		if (soundLoader == null) {
			soundLoader = new SoundPlayer();
		}
		return soundLoader;
	}
}
